from django.db.models import Q
from django.shortcuts import render
import json
# Create your views here.
from django.views import View
from django.core import serializers
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from utils.resFormatUtil import ResFormat
from .models import Menu, Commodity, Column, CommodityInfo, CommodityImage
from elasticsearch import Elasticsearch

es = Elasticsearch([{"host": "127.0.0.1", "port": "9200"}])


class MenuView(View):
	@method_decorator(cache_page(10 * 60, cache='hotspot'))
	def get_menu(self, request):
		menu_query = Menu.objects.filter(status=0)
		menu_list = json.loads(serializers.serialize('json', menu_query, ensure_ascii=False))
		# 构造data
		data = {}
		for menu in menu_list:
			fields = menu['fields']
			fields['id'] = menu['pk']
			if not fields['superior']:  # 如果是父菜单
				data[menu['pk']] = {}
				data[menu['pk']]['fields'] = fields
			else:  # 如果是子菜单
				if data[fields['superior']].get('son'):
					data[fields['superior']]['son'].append(fields)
				else:  # 父菜单还没有其他子菜单，直接赋值
					data[fields['superior']]['son'] = [fields, ]
		data = [i for i in list(data.values()) if i.get('fields')]
		# data = list(data.values())
		return ResFormat(data=data).json_response()
	
	def get(self, request, func):
		if hasattr(self, func):
			func = getattr(self, func)
			return func(request)
		else:
			return ResFormat(status='PARAM_ERROR').json_response()
	
	def update(self, request):
		menu_query = Menu.objects.filter(status=0)
		menu_list = json.loads(serializers.serialize('json', menu_query, ensure_ascii=False))
		for menu in menu_list:
			es.index(index='menu', body=menu['fields'], id=menu['pk'])
		data = menu_list
		return ResFormat(data=data).json_response()
	
	def delete(self, request):
		
		return ResFormat(data='delete').json_response()
	
	def search(self, request):
		search = request.GET.get('search')
		query = {
			"query": {"match": {
				"name": search
			}},
			"highlight": {
				"fields": {"name": {}},
				"pre_tags": "<span style='color:#f40'>",
				"post_tags": "</span>"
			},
			"_source": ["name"]  # 过滤字段
		}
		data = es.search(index='menu', body=query)
		data = [{"_source": hit["_source"], "highlight": hit["highlight"], "_id": hit["_id"]} for hit in
		        data['hits']['hits']]
		return ResFormat(data=data).json_response()


class ColumnView(View):
	
	def get(self, request):
		
		column_query = Column.objects.filter(status=0).order_by('priority')
		column_list = json.loads(serializers.serialize('json', column_query, ensure_ascii=False))
		
		data = [column['fields'] for column in column_list]
		
		for i in range(len(column_list)):
			commdity_query = column_query[i].commodity.filter(status=0).order_by('priority')
			commdity_list = json.loads(serializers.serialize('json', commdity_query, ensure_ascii=False))
			
			data[i]['commodity_list'] = []
			for commodity in commdity_list:
				commodity['fields']['id'] = commodity['pk']
				data[i]['commodity_list'].append(commodity['fields'])
		
		return ResFormat(data=data).json_response()


class CommodityView(View):
	
	def get(self, request, func):
		if hasattr(self, func):
			func = getattr(self, func)
			return func(request)
		else:
			return ResFormat(status='PARAM_ERROR').json_response()
	
	def update(self, request):
		commodity_query = Commodity.objects.filter(status=0).order_by('priority')
		commodity_list = json.loads(serializers.serialize('json', commodity_query, ensure_ascii=False))
		for commodity in commodity_list:
			es.index(index='cyxmall', body=commodity['fields'], id=commodity['pk'])
		data = commodity_list
		return ResFormat(data=data).json_response()
	
	def delete(self, request):
		
		return ResFormat(data='delete').json_response()
	
	def search(self, request):
		search = request.GET.get('search')
		query = {
			"query": {"match": {
				"title": search
			}},
			"highlight": {
				"fields": {"title": {}},
				"pre_tags": "<span style='color:#f40'>",
				"post_tags": "</span>"
			}
		}
		data = es.search(index='cyxmall', body=query)
		menu_id_list = [hit["_source"]["menu"] for hit in data["hits"]["hits"]]
		should = [{"match": {"title": search}}]
		for i in menu_id_list:
			term = {
				"term": {
					"menu": i
				}
			}
			should.append(term)
		query = {
			"query": {
				"bool": {
					"should": should
				}
			},
			"highlight": {
				"fields": {"title": {}},
				"pre_tags": "<span style='color:#f40'>",
				"post_tags": "</span>"
			},
			"_source": ["title", "subtitle", "pic", "priority"]
		}
		data = es.search(index='cyxmall', body=query)
		data = [{"_source":hit["_source"],"highlight":hit.get("highlight",None),"_id":hit["_id"]} for hit in data['hits']['hits']]
		return ResFormat(data=data).json_response()
	
	def by_menu(self,request):
		id = request.GET.get('id')
		menu_id_list = [menu.id for menu in Menu.objects.filter(Q(status=0),Q(id=id)|Q(superior=id))]
		commodity_query = Commodity.objects.filter(status=0,menu_id__in=menu_id_list)
		commodity_list = json.loads(serializers.serialize('json', commodity_query, ensure_ascii=False))
		data = []
		for commodity in commodity_list:
			commodity['data'] = {}
			commodity['data']['_source'] = commodity['fields']
			commodity['data']['_id'] = commodity['pk']
			data.append(commodity['data'])
		# data = commodity_list
		return ResFormat(data=data).json_response()
	


class CommodityInfoView(View):
	def get(self, request, func):
		if hasattr(self, func):
			func = getattr(self, func)
			return func(request)
		else:
			return ResFormat(status='PARAM_ERROR').json_response()
		
	def get_options(self,request):
		id = request.GET.get('id')
		options_query = CommodityInfo.objects.filter(status=0,commodity_id=id)
		options_list =json.loads(serializers.serialize('json', options_query, ensure_ascii=False))
		data = {}
		for option in options_list:
			fields = option['fields']
			key = fields['option_name']
			if not data.get(key,None):
				data[key] = []
			data[key].append({
				"options":fields['options'],
				"price": fields['price'],
				"inventory": fields['inventory'],
				"image": fields['image'],
				"id": option['pk']
			})
		data = list(data.items())
		data.sort(key=lambda x:len(x[0]))
		# data = options_list
		return ResFormat(data=data).json_response()
	
	def by_id(self,request):
		id = request.GET.get('id')
		commodity_query = Commodity.objects.filter(status=0, id=id)
		commodity_list = json.loads(serializers.serialize('json', commodity_query, ensure_ascii=False))
		data = commodity_list[0]['fields']
		return ResFormat(data=data).json_response()
	
	def by_src(self,request):
		get = request.GET
		id = get.get('id')
		belong = get.get('belong')
		img_query = CommodityImage.objects.filter(status=0, commodity_id=id, belong=belong)
		img_list = json.loads(serializers.serialize('json', img_query, ensure_ascii=False))
		data = [i['fields'] for i in img_list]
		return ResFormat(data=data).json_response()
